package com.tjec.project.workflow.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.CODESET_INCOMPATIBLE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tjec.project.workflow.mapper.BmsWorkflowMapper;
import com.alibaba.druid.stat.TableStat.Name;
import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.utils.ServletUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.project.businessWorkbench.domain.BmsBusiness;
import com.tjec.project.businessWorkbench.domain.BmsBusinessDocArchive;
import com.tjec.project.businessWorkbench.domain.BmsProjectDocCatalog;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessDocArchiveMapper;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessMapper;
import com.tjec.project.businessWorkbench.mapper.BmsProjectDocCatalogMapper;
import com.tjec.project.businessWorkbench.service.IBmsBusinessService;
import com.tjec.project.businessWorkbench.service.IBmsProjectDocCatalogService;
import com.tjec.project.msg.service.MsgService;
import com.tjec.project.projectWorkbench.domain.CancleReportNoVo;
import com.tjec.project.projectWorkbench.mapper.BmsAgencyNoMapper;
import com.tjec.project.projectWorkbench.mapper.BmsCostNoMapper;
import com.tjec.project.projectWorkbench.mapper.BmsReportNoMapper;
import com.tjec.project.system.domain.BmsMdBusinessCategory;
import com.tjec.project.system.domain.BmsReportType;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.mapper.BmsMdBusinessCategoryMapper;
import com.tjec.project.system.mapper.BmsMdWorkflowConfigMapper;
import com.tjec.project.system.mapper.BmsReportTypeMapper;
import com.tjec.project.system.mapper.SysUserMapper;
import com.tjec.project.system.mapper.SysUserRoleMapper;
import com.tjec.project.system.service.impl.SysUserServiceImpl;
import com.tjec.project.workflow.domain.BmsWorkflow;
import com.tjec.project.workflow.domain.dto.WorkflowParamsDto;
import com.tjec.project.workflow.domain.vo.BmsAttachmentsVo;
import com.tjec.project.workflow.domain.vo.BmsCatalogsVo;
import com.tjec.project.workflow.domain.vo.BmsWorkflowVo;
import com.tjec.project.workflow.service.IBmsWorkflowService;

/**
 * 项目流程Service业务层处理
 * 
 * @author pangyongfeng
 * @date 2020-05-18
 */
@Service
public class BmsWorkflowServiceImpl implements IBmsWorkflowService {
	private static final Logger log = LoggerFactory.getLogger(BmsWorkflowServiceImpl.class);
	@Autowired
	private BmsWorkflowMapper bmsWorkflowMapper;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private IBmsProjectDocCatalogService bmsProjectDocCatalogService;

	@Autowired
	private BmsAttachmentMapper bmsAttachmentMapper;

	@Autowired
	private BmsBusinessMapper bmsBusinessMapper;

	@Autowired
	private BmsBusinessDocArchiveMapper bmsBusinessDocArchiveMapper;

	@Autowired
	private MsgService msgService;

	@Autowired
	private SysUserMapper sysUserMapper;
	
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	
	@Autowired
    private BmsCostNoMapper bmsCostNoMapper;
	
	@Autowired
    private BmsAgencyNoMapper bmsAgencyNoMapper;
	
	@Autowired
    private BmsReportNoMapper bmsReportNoMapper;
	
	 @Autowired
	 private BmsProjectDocCatalogMapper bmsProjectDocCatalogMapper;
	 
	 @Autowired
	 private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;
	 
	 @Autowired
	 private BmsReportTypeMapper bmsReportTypeMapper;
	 
	 @Autowired
	 private IBmsBusinessService bmsBusinessService;
	 
	 @Autowired
	 private BmsMdWorkflowConfigMapper bmsMdWorkflowConfigMapper;

	/**
	 * 查询项目流程列表
	 * 
	 * @param bmsWorkflow 项目流程
	 * @return 项目流程
	 */
	@Override
	public List<BmsWorkflow> selectBmsWorkflowList(BmsWorkflow bmsWorkflow) {
		return bmsWorkflowMapper.selectBmsWorkflowList(bmsWorkflow);
	}

	/**
	 * 新增项目流程
	 * 
	 * @param bmsWorkflow 项目流程
	 * @return 结果
	 */
	@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int insertBmsWorkflow(BmsWorkflowVo bmsWorkflow) {
		log.info("WorkflowCode=" + bmsWorkflow.getBizObjectSchemaCode() + ",BusinessId=" + bmsWorkflow.getBusinessId());
		if ("projectElectronicArchive".equals(bmsWorkflow.getBizObjectSchemaCode())) {

			BmsBusiness bmsBusiness = new BmsBusiness();
			bmsBusiness.setArchiveStatus("2");
			bmsBusiness.setGuid(bmsWorkflow.getBusinessId());
			int res = bmsBusinessMapper.updateBmsBusinessStatus(bmsBusiness);
			log.info("res=" + res);
			// 更新附件状态
			List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveMapper
					.selectDocArchiveAtt(bmsWorkflow.getBusinessId());
			
				log.info("list=" + list);
				List<String> ids = new ArrayList<String>();
				if (list != null && list.size() > 0) {
					list.forEach(item -> {
						ids.add(item.getGuid());
					});
				}
				log.info("ids=" + ids);
			if(ids!=null && ids.size()>0) {
				bmsAttachmentMapper.updateAttachmentStatusByGuid(ids, "2");
			}
			
		}
		// 发起后将下一节点审批人放入参与者
		bmsWorkflow.setParticipant(bmsWorkflow.getParticipantId());
		// 发送待办消息
		// sendMsgStartWorkflow(bmsWorkflow);
		Integer res = bmsWorkflowMapper.checkInstanceId(bmsWorkflow.getIntanceId());
		if(res==null || res==0) {
			return bmsWorkflowMapper.insertBmsWorkflow(bmsWorkflow);
		}else {
			return 1;
		}
		
	}

	/**
	 * 修改项目流程
	 * 
	 * @param bmsWorkflow 项目流程
	 * @return 结果
	 */
	@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public int updateBmsWorkflow(BmsWorkflowVo bmsWorkflow) {
		log.info("getBizObjectSchemaCode=" + bmsWorkflow.getBizObjectSchemaCode());
		log.info("getIntanceId=" + bmsWorkflow.getIntanceId());
		
		/*if(!"".equals(bmsWorkflow.getIntanceId()) && bmsWorkflow.getIntanceId()!=null && bmsWorkflow.getDisplayName()!=null && !"".equals(bmsWorkflow.getDisplayName())) {
			String auditor = bmsWorkflowMapper.getAuditor(bmsWorkflow.getIntanceId(), bmsWorkflow.getDisplayName());
			if(!"".equals(auditor) && auditor!=null) {
				String[] auditorArray = auditor.split(",");
				Set<String> auditorSet = new HashSet<String>();
				for (String string : auditorArray) {
					auditorSet.add(string);
				}
				auditorSet.add(bmsWorkflow.getParticipantId());

				bmsWorkflow.setParticipantId(StringUtils.join(auditorSet,","));
			}
		}*/
		
		if ("projectElectronicArchive".equals(bmsWorkflow.getBizObjectSchemaCode())) {// 归档流程
			BmsWorkflow resEntity = bmsWorkflowMapper.selectBmsWorkflowByInstanceId(bmsWorkflow.getIntanceId());

			log.info("getInstanceState=" + bmsWorkflow.getInstanceState());
			if ("1".equals(bmsWorkflow.getInstanceState())) {
				BmsBusiness bmsBusiness = new BmsBusiness();
				bmsBusiness.setArchiveStatus("1");
				bmsBusiness.setGuid(resEntity.getBusinessId());
				int res1 = bmsBusinessMapper.updateBmsBusinessStatus(bmsBusiness);
				log.info("res1=" + res1);
				// 更新附件状态
				List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveMapper
						.selectDocArchiveAtt(resEntity.getBusinessId());
				List<String> ids = new ArrayList<String>();
				if (list != null && list.size() > 0) {
					list.forEach(item -> {
						ids.add(item.getGuid());
					});
				}
				if(ids!=null && ids.size()>0) {
					bmsAttachmentMapper.updateAttachmentStatusByGuid(ids, "1");
				}

			} else if ("2".equals(bmsWorkflow.getInstanceState())) {
				BmsBusiness bmsBusiness = new BmsBusiness();
				bmsBusiness.setArchiveStatus("0");
				bmsBusiness.setGuid(resEntity.getBusinessId());
				int res2 = bmsBusinessMapper.updateBmsBusinessStatus(bmsBusiness);
				log.info("res2=" + res2);
				// 更新附件状态
				List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveMapper
						.selectDocArchiveAtt(resEntity.getBusinessId());
				List<String> ids = new ArrayList<String>();
				if (list != null && list.size() > 0) {
					list.forEach(item -> {
						ids.add(item.getGuid());
					});
				}
				if(ids!=null && ids.size()>0) {
					bmsAttachmentMapper.updateAttachmentStatusByGuid(ids, "0");
				}
			}

		} else if ("projectElectronicUnlock".equals(bmsWorkflow.getBizObjectSchemaCode())
				&& "1".equals(bmsWorkflow.getInstanceState())) {// 归档解锁流程
			BmsWorkflow resEntity = bmsWorkflowMapper.selectBmsWorkflowByInstanceId(bmsWorkflow.getIntanceId());

			BmsBusiness bmsBusiness = new BmsBusiness();
			bmsBusiness.setArchiveStatus("0");
			bmsBusiness.setGuid(resEntity.getBusinessId());
			int res3 = bmsBusinessMapper.updateBmsBusinessStatus(bmsBusiness);
			log.info("res3=" + res3);
			// 更新附件状态
			List<BmsBusinessDocArchive> list = bmsBusinessDocArchiveMapper
					.selectDocArchiveAtt(resEntity.getBusinessId());
			List<String> ids = new ArrayList<String>();
			if (list != null && list.size() > 0) {
				list.forEach(item -> {
					ids.add(item.getGuid());
				});
			}
			if(ids!=null && ids.size()>0) {
				bmsAttachmentMapper.updateAttachmentStatusByGuid(ids, "0");
			}

		}

		// 发起后将下一节点审批人放入参与者
		bmsWorkflow.setParticipant(bmsWorkflow.getParticipantId());
		// 发送短信待办提醒
		// sendMsgStartWorkflow(bmsWorkflow);
		return bmsWorkflowMapper.updateBmsWorkflow(bmsWorkflow);
	}

	@Override
	public WorkflowParamsDto getBpmParams(BmsWorkflow bmsWorkflow) {
		String members = bmsWorkflowMapper.getMembers(bmsWorkflow.getProjectId());
		WorkflowParamsDto res = bmsWorkflowMapper.getBpmParams(bmsWorkflow);
		res.setMembers(members);
		return res;
	}

	@Override
	public String createCatalog(BmsCatalogsVo bmsCatalogsVo) {
		if (bmsCatalogsVo != null && bmsCatalogsVo.getBmsCatalogVos() != null
				&& bmsCatalogsVo.getBmsCatalogVos().size() > 0) {
			String guid = bmsProjectDocCatalogService.selectDocCatalog(bmsCatalogsVo.getBusinessId(), "3");

			Map<String, String> map = new HashMap<String, String>();

			bmsCatalogsVo.getBmsCatalogVos().forEach(item -> {
				if ("1".equals(item.getType())) {
					String name = bmsMdWorkflowConfigMapper.getNameByUrl(item.getCatalogName());
					BmsProjectDocCatalog catalog = bmsProjectDocCatalogService.selectCatalogByParentIdAndName(guid,
							name);
					if (catalog != null) {
						map.put("parentId", catalog.getGuid());
					} else {
						BmsProjectDocCatalog bmsProjectDocCatalog = new BmsProjectDocCatalog();
						bmsProjectDocCatalog.setBusinessId(bmsCatalogsVo.getBusinessId());
						bmsProjectDocCatalog.setName(name);
						bmsProjectDocCatalog.setParentId(guid);
						bmsProjectDocCatalog.setIsEdit("3");
						bmsProjectDocCatalogService.insertBmsProjectDocCatalog(bmsProjectDocCatalog);
						map.put("parentId", bmsProjectDocCatalog.getGuid());
					}
				}

			});

			bmsCatalogsVo.getBmsCatalogVos().forEach(item -> {
				if ("0".equals(item.getType())) {
					BmsProjectDocCatalog bmsProjectDocCatalog = new BmsProjectDocCatalog();
					bmsProjectDocCatalog.setBusinessId(bmsCatalogsVo.getBusinessId());
					bmsProjectDocCatalog.setName(item.getCatalogName());
					bmsProjectDocCatalog.setParentId(map.get("parentId"));
					bmsProjectDocCatalog.setIsEdit("3");
					bmsProjectDocCatalogService.insertBmsProjectDocCatalog(bmsProjectDocCatalog);
					map.put("returnGuid", bmsProjectDocCatalog.getGuid());
				}
			});

			return map.get("returnGuid");
		} else {
			return null;
		}

	}

	@Override
	public int insertAttachments(BmsAttachmentsVo bmsAttachmentsVo) {

		if (bmsAttachmentsVo != null && bmsAttachmentsVo.getBizId() != null
				&& !StringUtils.isBlank(bmsAttachmentsVo.getBizId())) {
			String bizId = bmsAttachmentsVo.getBizId();
			// 删除附件
			bmsAttachmentMapper.deleteBmsAttachmentByBizId(bizId);
			String flag = AttachmentConstants.AUDIT;
			// 添加附件
			if (bmsAttachmentsVo.getBmsAttachments() != null && bmsAttachmentsVo.getBmsAttachments().size() > 0) {
				bmsAttachmentsVo.getBmsAttachments().forEach(item -> {
					item.setCategory(flag);
					item.setBizId(bizId);
					
					bmsProjectDocCatalogMapper.updateBmsProjectDocCatalogCountsPlus(bizId);
				});
				int res = bmsAttachmentMapper.batchInsertAttachments(bmsAttachmentsVo.getBmsAttachments());
				return res;
			} else {
				return 0;
			}
		} else {
			return 0;
		}
	}

	@Override
	public String getMembers(String projectId) {
		return bmsWorkflowMapper.getMembers(projectId);
	}

	// 发起流程
	public void sendMsgStartWorkflow(BmsWorkflowVo bmsWorkflow) {
		// 当前审批人工号
		String jobNo = bmsWorkflow.getParticipantId();
		log.info("新发流程，当前审批人工号=" + jobNo);

		SysUser user = sysUserMapper.selectUserByJobNo(jobNo);
		log.info("新发流程，当前审批人信息=" + user);

		msgService.SendMsg2(user.getPhonenumber(), "您有一条新的待办流程，请尽快处理！");
	}

	// 审批流程
	public void sendMsgApproveWorkflow(BmsWorkflowVo bmsWorkflow) {
		// 当前审批人工号
		String jobNo = bmsWorkflow.getParticipantId();
		log.info("新发流程，当前审批人工号=" + jobNo);

		SysUser user = sysUserMapper.selectUserByJobNo(jobNo);
		log.info("新发流程，当前审批人信息=" + user);

		msgService.SendMsg2(user.getPhonenumber(), "您有一条新的待办流程，请尽快处理！");
	}
	
	@Override
	public int cancleReportNo(CancleReportNoVo cancleReportNoVo) {
		int result = 0;
		if(cancleReportNoVo!=null && StringUtils.isNotBlank(cancleReportNoVo.getReportType()) && StringUtils.isNotBlank(cancleReportNoVo.getGuid())) {
			String reportType = cancleReportNoVo.getReportType();
			String guid = cancleReportNoVo.getGuid();
			//0:咨询报告号
			if("0".equals(reportType)) {
				result= bmsReportNoMapper.deleteBmsReportNoByGuid(guid);
			}
			//1:招标代理号
			if("1".equals(reportType)) {
				result = bmsAgencyNoMapper.deleteBmsAgencyNoByGuid(guid);
			}
			//2:造价报告号
			if("2".equals(reportType)) {
				result = bmsCostNoMapper.deleteBmsCostNoByGuid(guid);
			}
		}
		return result;
	}

	@Override
	public Integer checkTookPartIn(String jobNo, String instanceId) {
		Integer res = bmsWorkflowMapper.checkTookPartIn(jobNo, instanceId);
		if(res!=null && res>0) {
			return 1;//是参与者
		}else {
			return 2;//不是参与者
		}
	}

	@Override
	public String updateBmsBusinessStatus(BmsBusiness bmsBusiness) {
		//1、判断是否是造价报告和咨询报告
		//2、如果是多个报告号，则不更新
		BmsMdBusinessCategory businessType = bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryByGuId(bmsBusiness.getBusinessCategoryId());
	    if(businessType!=null && StringUtils.isNotBlank(businessType.getReportNoApply()) && !"2".equals(businessType.getReportNoApply())) {
	    	BmsReportType bmsReportType = new BmsReportType();
	    	bmsReportType.setBusinessTypeId(bmsBusiness.getBusinessCategoryId());
	    	List<BmsReportType> resList = bmsReportTypeMapper.selectBmsReportTypeList(bmsReportType);
	    	if(resList!=null && resList.size()==1) {
	    		bmsBusinessService.updateBmsBusiness(bmsBusiness);
	    	}
	    }
		return null;
	}

}
